package leetcode.秋招.深信服;

import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author ：zsy
 * @date ：Created 2021/9/18 19:49
 * @description：
 */



public class Solution {

    @Test
    public void Test() {
        System.out.println(reverseWords("This is sangfor.",1));
    }
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     * <p>
     * 给定一行英文句子和一个数字i，将第1个至第i个单词的顺序翻转，将第i+1个至最后一个单词的顺序翻转，单词内字符的顺序不变。为简单起见，标点符号和普通字母一样处理。
     *
     * @param s string字符串 输入字符串
     * @param i int整型 序号
     * @return string字符串
     */
    public String reverseWords(String s, int i) {
        // write code here
        String[] strings = s.split(" ");
        StringBuilder builder = new StringBuilder();
        if (i <= 0 || i >= strings.length) {
            for (int j = strings.length - 1; j >= 0 ; j--) {
                builder.append(strings[j] + " ");
            }
            return builder.toString().trim();
        } else {
            StringBuilder builder1 = new StringBuilder();
            StringBuilder builder2 = new StringBuilder();
            for (int j = 0; j < i; j++) {
                builder1.append(strings[j] + " ");
            }
            for (int j = i; j < strings.length; j++) {
                builder2.append(strings[j] + " ");
            }
            String s1 = reverseWords(builder1.toString());
            String s2 = reverseWords(builder2.toString());
            return s1 + " " + s2;
        }
    }

    public String reverseWords(String s) {
        s = s.trim();
        List<String> wordList = Arrays.asList(s.split("\\s+"));
        Collections.reverse(wordList);
        return String.join(" ", wordList);
    }
}